package com.yjkf.zh.admin.controller;

import com.yjkf.zh.admin.aspect.LogAnnotation;
import com.yjkf.zh.admin.dao.SysDeviceMapper;
import com.yjkf.zh.admin.dao.SysProductMapper;
import com.yjkf.zh.admin.model.SysProduct;
import com.yjkf.zh.admin.service.SysProductService;
import com.yjkf.zh.core.http.HttpResult;
import com.yjkf.zh.core.page.PageRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("product")
public class SysProductController {

    @Autowired
    private SysProductService sysProductService;

    @Autowired
    private SysDeviceMapper sysDeviceMapper;

    @Autowired
    private SysProductMapper sysProductMapper;

    @PreAuthorize("hasAuthority('sys:product:view')")
    @PostMapping("/findPage")
  //  @LogAnnotation(content = "查看产品列表")
    public HttpResult findPage(@RequestBody PageRequest pageRequest){
        return HttpResult.ok(sysProductService.findPage(pageRequest));
    }

    @PreAuthorize("hasAuthority('sys:product:add') AND hasAuthority('sys:product:edit')")
    @PostMapping("/save")
    @LogAnnotation(content = "添加产品")
    public HttpResult save(@RequestBody SysProduct sysProduct){
        return HttpResult.ok(sysProductService.save(sysProduct));
    }

    @PreAuthorize("hasAuthority('sys:product:delete')")
    @PostMapping("/delete")
    @LogAnnotation(content = "删除产品")
    public HttpResult delete(@RequestBody List<SysProduct> sysProduct){
        for(SysProduct sysProduct1:sysProduct){
            Long id = sysProduct1.getId();
            if(!sysDeviceMapper.findDeviceForProductId(id).isEmpty()){
                return HttpResult.error("产品下存在设备，请解绑后在进行删除操作！");
            }
        }
        return HttpResult.ok(sysProductService.delete(sysProduct));
    }


    @PreAuthorize("hasAuthority('sys:product:view')")
    @GetMapping("/findAll")
    public HttpResult findAll(){
        return HttpResult.ok(sysProductService.findAll());
    }


    @PreAuthorize("hasAuthority('sys:adminDevice:view')")
    @GetMapping(value="/queryDeviceDetail")
    //@LogAnnotation(content = "查询三元组")
    public HttpResult queryDeviceDetail(@RequestParam Long productId){
        SysProduct sysProduct = sysProductMapper.selectKeyForId(productId);
        return HttpResult.ok(sysProduct);
    }
}
